﻿if (!exports) {
    var exports = {}
}
(function (e, c, f) {
    var a = c;
    if (!a) {
        var a = {}
    } 
    (function (g, h) {
        if (!g.browser) {
            g.browser = {}
        }
        g.browser.extension = {
            sendRequest: function (j, i) {
                if (typeof i == "undefined") {
                    i = function () { }
                }
                chrome.extension.sendRequest(j, i)
            },
            onRequest: {
                addListener: function (i) {
                    chrome.extension.onRequest.addListener(i)
                },
                removeListener: function (i) {
                    chrome.extension.onRequest.removeListener(i)
                }
            },
            getURL: function (i) {
                return chrome.extension.getURL(i || "")
            }
        }
    })(a);

    var u = c.browser.extension;
    if(!a.Notification){
        a.Notification = function(){};
    }
    a.Notification.prototype = {
        init: function(){
            this.renderFollow();
            this.registerEvents()
        },
        registerEvents: function (){
            var q = this;
            //var _t = {url: window.location.href};
            var _t = {url: window.location.protocol + "//" +window.location.host + window.location.pathname};
            var sites;
            var confKey = '360buy.com';
//            q.url2key(null, _t.url, function(key){
//                confKey = key;
//            });
            $("#jingdongAssistBar").live('click', function (r) {
                r.preventDefault();

                $('#jingdongAssistBar').find('img').popover('show');
                $('div.popover:eq(0)').find('ul>li:eq(0)>a').live('click', function(){
                });
                $('div.popover:eq(0)').find('ul>li:eq(1)>a').live('click', function(){
                    u.sendRequest({
                        topic: "open_tab",
                        url: "options.html"
                    }, function(){});
                });

                $('div.popover').live('mouseleave', function(r){
                    $('div.popover').remove();
                    u.sendRequest({
                            topic: "get_data"
                        },function(s){
                            sites = s;
                            if (confKey && q.checkUrl(sites, confKey, _t.url)){
                                $('#jingdongAssistBar').find('img').remove();
                            }
                    });
                }).css('z-index', 2);

                $('div[c=rank]').stars({
                    inputType: "select",
                    split: 1
                });

                
                //$('#pagebody').ready(function(){
                    //$('#pagebody').css('width', '350px').css('height', '250px');
            
                    $('div[c=rank]').stars('select', 4).stars({
                        inputType: "select",
                        split: 1,
                        captionEl: $('#captionEl')
                    });

                    var imageUrl = u.getURL('img/jquery.ui.stars.gif');
                    $('.ui-stars-star a,.ui-stars-cancel a').css('background-image', 'url(' + imageUrl + ')');

                        u.sendRequest({
                            topic: "get_data"
                        },function(s){
                            sites = s;
                            if (confKey && q.checkUrl(sites, confKey, _t.url)) {
//                                //已有数据 画图
//                                $('body').width(350).height(250);
//                                q.drawChart(q.getPrices(sites, confKey, _t.url), 'chart_div');
//                                var rank = q.getRank(sites, confKey, _t.url);
//                                var starWrapper = $('div[c=rank]');
//                                console.log(rank);

//                                q.setRank(sites, rank, starWrapper);
//                                site.getPageInfo({
//                                    tab: _t,
//                                    success: function (_info) {
//                                        //更新本url相关的数据信息
//                                        _info.rank = rank;
//                                        console.log(JSON.stringify(_info));
//                                        site.handle.updateSiteData(_t.url, _info);
//                                    }
//                                });
//                                $('#action_div').append(
//                                    $('<button>').text('删除关注').click(function () {
//                                        $(this).text('处理中').attr('disabled', 'true');
//                                        q.delUrl(confKey, _t.url);
//                                    })
//                                );
                            } else {

                                //stars
                                $('div[c=rank]').stars('select', 4).stars({
                                    //captionEl: $(this).prev('div').find('span[c=rankvalue]')
                                    captionEl: $('#captionEl')
                                });

                                //没有关注 显示添加关注选项
                                if($('#action_div').find('<button>').length == 0)
                                {
                                    $('#action_div').append(
                                        $('<button>').attr('id', 'btnAddUrl').text('加关注').attr('class', 'btn btn-primary').click(function () {
                                            $(this).text('处理中').attr('disabled', 'true');
                                            q.addUrl(confKey, _t.url, function(){
                    console.log(2111);
                                            q.getPageInfo(confKey, _t.url, function(){
                                            
                                            $('#btnAddUrl').text('关注完成').attr('disabled', 'true').attr('class', 'btn btn-success')
                                        
                    console.log(3111);});
                                            });
                                        })
                                    );
                                }
//                                $('#btnAddUrl').attr('class', 'btn-coll');
//                                var imageUrl = u.getURL('img/icon2011111801.png');
//                                $('#btnAddUrl').css('background-image', 'url(' + imageUrl + ')');
                            }
                        });
                });
//            });
        },
        renderFollow: function(){
            var q = this;
            var _t = {url: window.location.protocol + "//" +window.location.host + window.location.pathname};
            var sites;
            var confKey = '360buy.com';
            
//            var confKey;
//            q.url2key(null, _t.url, function(key){
//                confKey = key;
//            });
            u.sendRequest({
                            topic: "get_data"
                        },function(s){
                            sites = s;
                        if (!(confKey && q.checkUrl(sites, confKey, _t.url))) {
                            q.getTemplate(function(h)
                            {
                                $('#promotion1').nextUntil('div.clr', 'a[clstag*="jiangjia"]').remove();
                                $('#promotion1').after(h);

                                u.sendRequest({
                                    topic: "get_bar",
                                    url: "img/arrow.gif"
                                }, function(data){
                                    var url = data.url;
                                    var followProductTmpl = data.tmpl;
                                    var popoverContent = [followProductTmpl].join('');
                                    $('#jingdongAssistBar').find('img')
                                                            .popover({
                                                                trigger: 'manual',
                                                                title: '京东“实惠购”',
                                                                content: popoverContent
                                                            })
                                                            .attr('src', url);
                                });
                            });
                        }
            });
        },
        getTemplate: function (w) {
                u.sendRequest({
                    topic: "get_template",
                    page: "assets/bar.htm"
                }, w);
        },

        url2key: function (domain, url, w) {
            u.sendRequest({
                topic: 'get_url2key',
                url: url
            }, w);
        },
        getPrices: function(sites, confKey, url){
            if (sites[confKey] && sites[confKey][url])
                return sites[confKey][url].price.slice(0);
            return [];
        },
        getRank: function(sites, confKey, url){
            var rank = 4;
            if (sites[confKey] && sites[confKey][url]) {
                rank = sites[confKey][url].rank;
            }
            return rank;
        },
        checkUrl: function(sites, confKey, url){
            return (sites[confKey] && sites[confKey][url]);
        },
        addUrl: function(confKey, url, callback){
            u.sendRequest({
                        topic: "add_url",
                        confKey: confKey,
                        url: url
                    },callback);
        },
        getPageInfo: function(confKey, url, callback){
            var rank = this.getStarValue('rankStar');
                u.sendRequest({
                    topic: "get_pageInfo",
                    confKey: confKey,
                    url: url,
                    rank: rank
                }, callback);
        },
        delUrl: function(confKey, url){
            u.sendRequest({
                        topic: "del_url",
                        confKey: confKey,
                        url: url
                    },function(){
            location.reload(true);
            });
        },
        drawChat:function(data){
                var xAxis = [], yAxis = [], time;
                for (var i = 0; i < data.length; i++) {
                    time = new Date(data[i][0]);
                    xAxis.push(time.getDate() + '/' + (time.getMonth() + 1));
                    yAxis.push(data[i][1] - 0);
                }
                return new Highcharts.Chart({
                    chart: {
                        renderTo: divId,
                        defaultSeriesType: 'line',
                        height: 200,
                        width: 300,
                        spacingTop: 20,
                        marginRight: 80,
                        marginBottom: 25
                    },
                    title: {
                        text: '历史价格',
                        x: -20 //center
                    }, /*
                    subtitle: {
                        text: 'Source: WorldClimate.com',
                        x: -20
                    },*/
                    xAxis: {
                        categories: xAxis
                    },
                    yAxis: {
                        title: {
                            text: '价格'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.series.name + '</b><br/>' +
                            this.x + ': ￥' + this.y + '';
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 100,
                        borderWidth: 0
                    },
                    series: [{
                        name: '价格',
                        data: yAxis
                    }]
                });
        },
        getStarValue: function (starwrapperId) {
                var ui = $("#" + starwrapperId).data("stars");
                // Read options
                var currValue = ui.options.value; // Get current Value

                return currValue || 4;
            },
        setRank: function(rank, starWraper) {
                $(starWraper).stars('select', rank).stars({
                    captionEl: $('#captionEl')
                });
            },
        showPopup: function(url, w){
                u.sendRequest({
                    topic: "show_popup",
                    url: url
                }, w);
        },
        hidePopup: function(){
                u.sendRequest({
                    topic: "hide_popup"
                }, w);
        }
    };
    var b = new a.Notification();
    b.init();

    if(!a.Follow){
        a.Follow = function(){};
    }

    a.Follow.prototype = {
        init: function(){
            this.renderEnabledSearchEngines();
            this.registerEvents()
        },
        registerEvents: function () {
            
        },
        renderEnabledSearchEngines: function(){
            
        }
    };
})(window, exports);